import { getCourseList, postPlanDataList } from '@/api/StatisticsApi';
import {
  assHistoryStudyDetailExportNew,
  entHistoryStudyDetailExportNew,
  getCycleByPlan,
  getHistoryStudyDetailList,
  HistoryListItem,
  HistoryListSearchParams,
} from '@/api/StatisticsApi/history';
import { WaitDealContext } from '@/layouts/BasicLayout';
import { useAppSelector } from '@/redux/store';
import { useRequest } from 'ahooks';
import { Button, Cascader, Form, message } from 'antd';
import { useContext, useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import type { YmColumnsType } from 'ym-design';
import { YmAddPageLayout, YmTable, type YmAddPageLayoutProps } from 'ym-design';
import { getAssociationTreeData } from '../components/StudyStatisticsSelect/data';
const { PaneItem } = YmAddPageLayout;

type SearchValue = Partial<HistoryListSearchParams>;
type TableRecord = HistoryListItem;
interface Option {
  value: string | number;
  label: string;
  children?: Option[];
}

export default function StudyPlanPage() {
  const { flyInStart, requestFlyIn } = useContext(WaitDealContext);
  const navigator = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();
  const [initPage, setInitPage] = useState<number>(0);
  const [canPost, setCanPost] = useState(true);
  const [resultData, setResultData] = useState<{ list: TableRecord[]; total: number }>({
    list: [],
    total: 0,
  });
  // organizationType -  1: 协会; 0: 企业
  const personId = useAppSelector((state) => state.loginUser.personId);
  const { entId, organizationType } = useAppSelector((state) => state.loginEnt);
  const [searchValue, setSearchValue] = useState<HistoryListSearchParams>();
  const [form] = Form.useForm();

  const [force, _forceUpdate] = useState<number>();

  const [parentId, setParentId] = useState<string>(entId);
  const [selectPlanId, setSelectPlanId] = useState<string>();
  const [showSelect, setShowSelect] = useState<boolean>(false); // 是否可以显示select了 不加这个默认值选中不了
  const [selectCycleId, setSelectCycleId] = useState<string>();
  const [cycleList, setCycleList] = useState<{ label: string; value: string }[]>([]);

  const [associationPlanOptions, setAssociationPlanOptions] = useState<Omit<Option, 'children'>[]>([]);
  const [entPlanOptions, setEntPlanOptions] = useState<Option[]>([]);

  const forceUpdate = () => {
    _forceUpdate(Math.random());
  };

  const getPlanOptions = async () => {
    if (organizationType === 1) {
      // 协会
      const response = await getCourseList(entId);

      if (response && response.length) {
        setAssociationPlanOptions(
          response.map((item) => {
            return {
              label: item.name,
              value: item.courseGuid,
            };
          }),
        );

        setSelectPlanId(response[0].courseGuid);
        form.setFieldValue('planId', response[0].courseGuid);
      }
    } else {
      // 企业
      const response = await getAssociationTreeData({ entId, type: 1, count: false });

      const tempArray = response.list.map((item) => {
        return {
          label: item.name,
          value: item.entId,
          isLeaf: false,
        };
      });

      const planDataList = await postPlanDataList({
        pageNum: 1,
        pageSize: 99999,
        curEntId: parentId,
        entId,
      });

      const children = planDataList.map((item) => {
        return { label: item.name, value: item.courseGuid };
      });

      const newArray = [
        {
          label: '自建',
          value: entId,
          isLeaf: false,
          children,
        },
        ...tempArray,
      ];

      setEntPlanOptions(newArray);

      if (children.length > 0) {
        setSelectPlanId(children[0].value);
        form.setFieldValue('planOption', [parentId, children[0].value]);
        form.setFieldValue('planId', children[0].value);
      }
    }

    setShowSelect(true);
  };

  const loadData = async (selectedOptions: Option[]) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];

    const planDataList = await postPlanDataList({
      pageNum: 1,
      pageSize: 99999,
      curEntId: entId,
      entId: targetOption.value as string,
    });

    targetOption.children = planDataList.map((item) => {
      return { label: item.name, value: item.courseGuid };
    });

    setEntPlanOptions([...entPlanOptions]);
  };

  // 周期循环筛选项
  const getCycleByPlanTime = async () => {
    if (selectPlanId) {
      const response = await getCycleByPlan(selectPlanId);

      if (response && response.length > 0) {
        setCycleList(
          response.map((item) => {
            return { label: item.beginTime + '~' + item.endTime, value: item.cycleId };
          }),
        );

        setSelectCycleId(response[0].cycleId);
      } else {
        setCycleList([]);
        setSelectCycleId(undefined);
      }
    } else {
      setCycleList([]);
    }
  };

  useEffect(() => {
    getPlanOptions();
    setInitPage(1);
  }, []);

  useEffect(() => {
    getCycleByPlanTime();
  }, [selectPlanId]);

  useEffect(() => {
    if (selectCycleId) {
      if (organizationType === 1) {
        form.setFieldValue('planId', selectPlanId);
      } else {
        form.setFieldValue('planOption', [parentId, selectPlanId]);
        form.setFieldValue('planId', selectPlanId);
      }

      form.setFieldValue('cycleId', selectCycleId);

      if (initPage == 1) {
        setInitPage(2);
      } else {
        const m = initPage + 1;

        setInitPage(m);
      }

      forceUpdate();
    } else {
      form.setFieldValue('cycleId', undefined);
    }
  }, [selectCycleId]);

  // 表格数据
  const columns: YmColumnsType<TableRecord> = useMemo(
    () => [
      {
        title: '计划名称',
        dataIndex: 'name',
        key: 'name',
        width: 200,
        ellipsis: true,
        fixed: 'left',
      },
      {
        title: '学习周期',
        dataIndex: 'title',
        key: 'title',
        width: 120,
        ellipsis: true,
      },
      {
        title: '周期时间',
        dataIndex: 'startTime',
        key: 'startTime',
        width: 260,
        ellipsis: true,
        render: (text, record) => <span>{record.startTime + '-' + record.endTime}</span>,
      },
      {
        title: '姓名',
        dataIndex: 'personName',
        key: 'personName',
        width: 120,
        ellipsis: true,
      },
      {
        title: '电话号码',
        dataIndex: 'phone',
        key: 'phone',
        width: 120,
        ellipsis: true,
      },
      {
        title: '完成时间',
        dataIndex: 'finishTime',
        key: 'finishTime',
        width: 150,
        ellipsis: true,
      },
      {
        title: '学习状态',
        dataIndex: 'finishState',
        key: 'finishState',
        width: 80,
        ellipsis: true,
        render: (text, record) =>
          record.finishState == 2 ? (
            <span style={{ color: '#FF4A4A' }}>未学习</span>
          ) : (
            <span style={{ color: '#3BD59A' }}>已学习</span>
          ),
      },
    ],
    [],
  );

  const columns2: YmColumnsType<TableRecord> = useMemo(
    () => [
      {
        title: '计划名称',
        dataIndex: 'name',
        key: 'name',
        width: 300,
        ellipsis: true,
      },
      {
        title: '学习周期',
        dataIndex: 'title',
        key: 'title',
        width: 200,
        ellipsis: true,
      },
      {
        title: '周期时间',
        dataIndex: 'startTime',
        key: 'startTime',
        width: 300,
        ellipsis: true,
        render: (text, record) => <span>{record.startTime + '-' + record.endTime}</span>,
      },
      {
        title: '姓名',
        dataIndex: 'personName',
        key: 'personName',
        width: 120,
        ellipsis: true,
      },
      {
        title: '电话号码',
        dataIndex: 'phone',
        key: 'phone',
        width: 120,
        ellipsis: true,
      },
      {
        title: '入职企业',
        dataIndex: 'entName',
        key: 'entName',
        width: 180,
        ellipsis: true,
        hidden: organizationType === 0,
        render(value, record) {
          if (record.joinList && record.joinList.length) {
            const enterpriseNames = record.joinList.map((item) => item.name);
            const displayName = enterpriseNames[0];

            if (enterpriseNames.length > 1) {
              return (
                <div>
                  {displayName}等{enterpriseNames.length}家企业
                </div>
              );
            } else {
              return <div>{displayName}</div>;
            }
          } else {
            return <div style={{ color: '#f66e2c' }}>暂无入职企业</div>;
          }
        },
      },
      {
        title: '人员职位',
        dataIndex: 'positionName',
        key: 'positionName',
        width: 120,
        ellipsis: true,
        hidden: organizationType === 0,
        render(value, record) {
          const extraInfo = record?.extraInfo?.find((item) => item.title === '人员职位');

          return (
            <>
              <span>{extraInfo?.value ?? '--'}</span>
            </>
          );
        },
      },
      {
        title: '完成时间',
        dataIndex: 'finishTime',
        key: 'finishTime',
        width: 150,
        ellipsis: true,
      },
      {
        title: '学习状态',
        dataIndex: 'finishState',
        key: 'finishState',
        width: 80,
        ellipsis: true,
        render: (text, record) =>
          record.finishState == 2 ? (
            <span style={{ color: '#FF4A4A' }}>未学习</span>
          ) : (
            <span style={{ color: '#3BD59A' }}>已学习</span>
          ),
      },
    ],
    [],
  );

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          navigator(-1);
        },
      },
      destroyInactiveTabPane: false,
    }),
    [],
  );

  const { run: handleExport, loading: expoLoading } = useRequest(
    async (e) => {
      let params;
      if (organizationType === 1) {
        // 协会
        params = {
          pageIndex: 1,
          pageSize: 99999,
          personId: personId,
          entId,
          curEntId: searchValue?.curEntId,
          planId: searchValue?.planId,
          cycleId: searchValue?.cycleId,
          finishState: searchValue?.finishState,
        };
        requestFlyIn(e, '历史学习情况', assHistoryStudyDetailExportNew, params).then((res: any) => {
          if (res.suc) {
            //success doing
          }
        });
      } else {
        // 企业
        params = {
          pageIndex: 1,
          pageSize: 99999,
          personId: personId,
          entId: parentId,
          curEntId: entId,
          planId: searchValue?.planId,
          cycleId: searchValue?.cycleId,
          finishState: searchValue?.finishState,
        };
        requestFlyIn(e, '历史学习情况', entHistoryStudyDetailExportNew, params).then((res: any) => {
          if (res.suc) {
            //success doing
          }
        });
      }
      return true;
    },
    { manual: true },
  );
  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem tabKey="tab1" label="历史学习情况" className="pane_tab1" style={{ outline: 'none' }}>
        <div style={{ height: 'calc(100vh - 118px)', width: '100%' }}>
          <YmTable<TableRecord, SearchValue>
            wrapperStyle={{ background: '#fff' }}
            rowKey="No"
            columns={organizationType === 1 ? columns2 : columns}
            toolBar={{
              prefixNode: (
                <>
                  <Button
                    type="primary"
                    disabled={!searchValue || !searchValue?.planId}
                    loading={expoLoading}
                    onClick={(e) => {
                      handleExport(e);
                    }}
                  >
                    导出查询记录
                  </Button>
                </>
              ),
            }}
            searchForm={{
              hiddenReset: true,
              defaultCollapsed: true,
              formItems: [
                {
                  name: 'planId',
                  label: '计划名称',
                  hidden: organizationType === 0,
                  colProps: {
                    span: organizationType === 0 ? 0 : undefined,
                  },
                  valueType: {
                    type: 'select',
                    selectProps: {
                      placeholder: '请选择',
                      options: associationPlanOptions,
                      showSearch: false,
                      maxTagCount: 1,
                      onChange: (value) => {
                        setSelectPlanId(value);
                        form.setFieldValue('planId', value);
                      },
                    },
                  },
                },
                {
                  name: 'planOption',
                  label: '计划名称',
                  hidden: organizationType === 1,
                  colProps: {
                    span: organizationType === 1 ? 0 : undefined,
                  },
                  children: showSelect ? (
                    <Cascader
                      options={entPlanOptions}
                      loadData={loadData}
                      onChange={(value, option) => {
                        if (value && value.length > 0) {
                          setParentId(value[0] as string);
                          setSelectPlanId(value[1] as string);

                          form.setFieldValue('planId', value[1]);
                        }
                      }}
                      placeholder="请选择"
                    />
                  ) : undefined,
                },
                {
                  name: 'planId',
                  label: '计划名称',
                  hidden: true,
                  colProps: {
                    span: 0,
                  },
                },
                {
                  name: 'cycleId',
                  label: '周期时间',
                  valueType: {
                    type: 'select',
                    selectProps: {
                      options: cycleList,
                      showSearch: false,
                      maxTagCount: 1,
                      popupMatchSelectWidth: true,
                      placeholder: '请选择',
                    },
                  },
                },
                {
                  name: 'finishState',
                  label: '学习状态',
                  valueType: {
                    type: 'select',
                    selectProps: {
                      defaultValue: '',
                      options: [
                        { label: '全部', value: '' },
                        { label: '已学习', value: 1 },
                        { label: '未学习', value: 2 },
                      ],
                      showSearch: false,
                      maxTagCount: 1,
                      placeholder: '请选择',
                    },
                  },
                },
              ],
              form,
            }}
            request={async ({ page }, value = {}) => {
              let url, params;
              const { pageIndex, pageSize } = page;
              const m = initPage + 1;
              setInitPage(m);
              console.log('canPost,initPage', initPage);

              if (!canPost && initPage > 2) {
                console.log('执行了吗');
                messageApi.info('查询时间需间隔3s，请稍后重试！');
                return resultData;
              } else {
                setCanPost(false);
                setTimeout(() => {
                  setCanPost(true);
                }, 3000);
                const pid = value.planId ? value.planId : value.planOption?.[1];
                setSearchValue({ ...value, entId, planId: pid, pageIndex, pageSize });

                if (organizationType === 1) {
                  // 协会
                  params = {
                    ...value,
                    planId: pid,
                    entId,
                  };

                  url = '/safe/api/statistics/assHistoryStudyDetailList';
                } else {
                  // 企业
                  params = {
                    ...value,
                    planId: pid,
                    entId: parentId,
                    curEntId: entId,
                  };

                  url = '/safe/api/statistics/entHistoryStudyDetailList';
                }

                const response = await getHistoryStudyDetailList(url, params, page?.pageIndex, page?.pageSize);

                setResultData(response);

                return response;
              }
            }}
            requestOptions={{
              ready: selectCycleId ? true : false,
              reFreshDep: [force],
            }}
          />
          {contextHolder}
        </div>
      </PaneItem>
    </YmAddPageLayout>
  );
}
